package Socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/*
聊天室的服务器端
 */
public class Server2 {
    private ServerSocket serverSocket;

    public Server2() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println( "客户端"+socket.getInetAddress()+"已经连接");
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }

            /*服务器接收消息*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server2 server = new Server2();
        server.start();
    }

    /*
     * 定义内部类与客户端交互
     * */
    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;  //记录客户端IP地址

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                InetAddress inetAddress = socket.getInetAddress();
                String address=String.valueOf(inetAddress);
                String subAd=address.substring(address.lastIndexOf('.'),address.length());
                String message;
                try {
                    while ((message = br.readLine()) != null) {
                        System.out.println("Client ("+subAd+") ：" + message);
                    }
                } catch (IOException e) {
                    System.out.println("大概率是客户端"+subAd+"异常退出...");
                }
            } catch (IOException e) {

            }

        }
    }


}
